import { ethers, network } from "hardhat";

async function main() {
  if (network.name !== "localhost" && network.name !== "hardhat") {
    throw new Error("Use --network localhost for this script");
  }

  const [deployer, operator, treasury, injector] = await ethers.getSigners();

  console.log("部署账户:", deployer.address);
  console.log("操作员账户:", operator.address);
  console.log("金库账户:", treasury.address);
  console.log("注入账户:", injector.address);

  // 1) 部署 Mock CAKE
  console.log("正在部署 Mock CAKE...");
  const MockCake = await ethers.getContractFactory("MockCake");
  const cake = await MockCake.deploy();
  await cake.deployed();
  console.log("MockCake 已部署到:", cake.address);

  // 2) 部署 Mock RNG
  console.log("正在部署 Mock RandomNumberGenerator...");
  const MockRNG = await ethers.getContractFactory("MockRandomNumberGenerator");
  const rng = await MockRNG.deploy();
  await rng.deployed();
  console.log("MockRandomNumberGenerator 已部署到:", rng.address);

  // 3) 部署 Lottery
  console.log("正在部署 PancakeSwapLottery...");
  const Lottery = await ethers.getContractFactory("PancakeSwapLottery");
  const lotto = await Lottery.deploy(cake.address, rng.address);
  await lotto.deployed();
  console.log("PancakeSwapLottery 已部署到:", lotto.address);

  // 4) 互相绑定
  console.log("正在设置合约地址绑定...");
  await (await rng.setLotteryAddress(lotto.address)).wait();

  // 5) 设置 operator/treasury/injector
  console.log("正在设置操作员、金库和注入地址...");
  await (
    await lotto.setOperatorAndTreasuryAndInjectorAddresses(
      operator.address,
      treasury.address,
      injector.address
    )
  ).wait();

  console.log("\n=== 部署完成 ===");
  console.log("MockCake:", cake.address);
  console.log("MockRandomNumberGenerator:", rng.address);
  console.log("PancakeSwapLottery:", lotto.address);
  console.log("Operator:", operator.address);
  console.log("Treasury:", treasury.address);
  console.log("Injector:", injector.address);
  console.log("\n现在可以开始测试彩票功能了！");
}

main().catch((e) => {
  console.error('彩票合约部署报错', e);
  process.exit(1);
});